<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Retrieve get parameters.
 * @access public
 * @return array Returns an array of get values. Use defaults if nothing is submitted.
 */
function get_params($segment = 3)
{
    $ci = &get_instance();
    
    $get_params = $ci->uri->uri_to_assoc($segment);
    
    $limit      = isset( $get_params['limit'] )     ? $get_params['limit']      : $ci->get('limit');
    $offset     = isset( $get_params['offset'] )    ? $get_params['offset']     : $ci->get('offset');
    $sort       = isset( $get_params['sort'] )      ? $get_params['sort']       : $ci->get('sort');
    $order      = isset( $get_params['order'] )     ? $get_params['order']      : $ci->get('order');
    $case       = isset( $get_params['case'] )      ? $get_params['case']       : $ci->get('case');
    $envelope   = isset( $get_params['envelope'] )  ? $get_params['envelope']   : $ci->get('envelope');
    $fields     = isset( $get_params['fields'] )    ? $get_params['fields']     : $ci->get('fields');
    
    // validation
    $errors = array();
    
    // limit
    if( ! is_numeric($limit) && $limit != FALSE)
    {
        array_push($errors, 'Limit should only contain numeric values.');
    }
    
    // offset
    if( ! is_numeric($offset) && $offset != FALSE )
    {
        array_push($errors, 'Offset should only contain numeric values.');
    }
    
    // order
    if( $order != 'asc' && $order != 'desc' && $order != FALSE )
    {
        array_push($errors, 'Order should be asc or desc only');
    }
    
    // case
    if( $case != 'camel' && $case != 'snake' && $case != 'dash' && $case != 'pascal' && $case != FALSE)
    {
        array_push($errors, 'Case can only be dash, snake, camel or pascal');
    }
    
    // envelope
    if( $envelope != 'true' && $case != 'false' && $envelope != FALSE)
    {
        array_push($errors, 'Envelope can only be true or false');
    }
    
    if (count($errors) > 0)
    {
        format_response('failed', 400, 'Invalid Parameter', $errors);
    } else
    {
        $params = array();
        $params['limit']    = $limit    ? (int) $limit : NULL;
        $params['offset']   = $offset   ? (int) $offset : 0;
        $params['sort']     = $sort     ? $sort : NULL;
        $params['order']    = $order    ? $order : 'asc';
        $params['case']     = $case     ? $case : 'snake';
        $params['envelope'] = $envelope ? $envelope : TRUE;
        $params['fields']   = $fields   ? $fields : '*';

        $args = array();
        $all_params = array_merge( $ci->get(), $get_params );

        foreach( $all_params as $key => $param )
        {
            // GET params as POST params
            $_POST[$key] = $param;
            if( 
                $key !== 'limit' && 
                $key !== 'offset' && 
                $key !== 'sort' && 
                $key !== 'order' && 
                $key !== 'format' && 
                $key !== 'envelope' && 
                $key !== 'case' && 
                $key !== 'fields'
              )
            {
                if( $param !== NULL && $param !== '' && $param !== FALSE)
                {
                    $args[$key] = $param;
                } else 
                {
                    format_response('failed', 400, 'Invalid Parameter', array($key => 'Must have a value pair'));
                }
            }
        }

        $params['args'] = $args;
        return $params;
    }

}

/**
 * Validate user post values.
 * @access public
 * @return boolean True if all fields passed the validation. Otherwise false
 */
function post_params()
{
    $ci = &get_instance();
    $ci->load->library('form_validation');
    $ci->form_validation->set_error_delimiters('', '');
    
    $ci->form_validation
        ->set_rules('limit', 'limit', '')
        ->set_rules('offset', 'offset', '')
        ->set_rules('sort', 'sort', '')
        ->set_rules('order', 'order', '');

    if ( $ci->form_validation->run() === TRUE )
    {
        $params = array();
        $params['limit']    = set_value('limit')    ? set_value('limit')    : NULL;
        $params['offset']   = set_value('offset')   ? set_value('offset')   : 0;
        $params['sort']     = set_value('sort')     ? set_value('sort')     : NULL;
        $params['order']    = set_value('order')    ? set_value('order')    : 'asc';
        
        $args = array();
        foreach( $ci->input->post() as $key => $param )
        {
            if( $param !== 'limit' || $param !== 'offset' || $param !== 'sort' || $param !== 'order' || $param !== 'format')
            {
                $args[$key] = $param;
            }
        }
        $params['args'] = $args;
        
        return $params;
    }
    else
    {
        format_response('failed', 400, 'Invalid Parameter', $ci->form_validation->error_array());
    }
}

/**
 * Convert PUT parameters to POST parameters
 * @access public
 * @return array Returns array of PUT parameters
 */
function put_params()
{
    $ci = &get_instance();
    // PUT params as POST params for validation purposes
    foreach( $ci->put() as $key => $value )
    {
        $_POST[$key] = $value;
    }
    return $ci->put();
}

/**
 * Convert DELETE parameters to POST parameters
 * @access public
 * @return array Returns array of DELETE parameters
 */
function delete_params()
{
    $ci = &get_instance();
    
    // DELETE params as POST params for validation purposes
    foreach( $ci->delete() as $key => $value )
    {
        $_POST[$key] = $value;
    }
    return $ci->delete();
}

/**
 * Format response
 * @param string $status Status either success or failed
 * @param int $code Status codes
 * @param string $message Message to be shown.
 * @param array $errors An array of errors, if any.
 * @param array $items An array of items, if any.
 */
//function format_response($status = 'error', $code = 400, $message = 'Request Failed', $errors = NULL, $items = NULL)
//{
//    $ci = &get_instance();
//    
//    $params = $ci->input->post();
//    $case = isset( $params['case'] ) ? $params['case'] : 'snake';
//    
//    if( isset( $params['envelope'] ) && $params['envelope'] == TRUE  )
//    {
//        $ci->response_array[changeCase('status', $case)]   = $status;
//        $ci->response_array[changeCase('code', $case)]     = $code;
//        $ci->response_array[changeCase('message', $case)]  = $message;
//
//        if($errors)
//        {
//            $ci->response_array['errors'] = $errors;
//        }
//
//        if($items)
//        {
//            $ci->response_array['items'] = $items;
//        }
//
//        $ci->response($ci->response_array, $code);
//        
//    } else
//    {
//        if($errors)
//        {
//            $ci->response_array['errors'] = $errors;
//        }
//        if($items)
//        {
//            $ci->response_array['items'] = $items;
//        }
//        
//        $ci->response($ci->response_array, $code);
//    }
//}

function format_response($status = 'error', $code = 400, $message = 'Request Failed', $errors = NULL, $items = array())
{
    $ci = &get_instance();
    
    $params = $ci->input->post();

    $case = isset( $params['case'] ) ? $params['case'] : 'snake';
    $format = isset( $params['format'] ) ? $params['format'] : 'xml';
    
    $response_array = array();

    if( isset( $params['envelope'] ) && $params['envelope'] == TRUE  )
    {
        $response_array[changeCase('status', $case)]   = $status;
        $response_array[changeCase('code', $case)]     = $code;
        $response_array[changeCase('message', $case)]  = $message;

        if($errors)
        {
            $response_array['errors'] = $errors;
        }

        if($items)
        {
            $response_array['items'] = $items;
        }

        $ci->response($response_array, $code);
        
    } else
    {
        if($errors)
        {
            $response_array['errors'] = $errors;
        }
        if($items)
        {
            $response_array['items'] = $items;
        }
        
        $ci->response($response_array, $code);
    }
}

/**
 * Formats string for valid json_encode
 * @param string $data String to be encoded
 * @return string Returns string with valid html characters
 */
function clean($data)
{
    $encode = mb_check_encoding($data, 'UTF-8') ? $data : utf8_encode($data);	
    $decoded = html_entity_decode($encode, ENT_QUOTES, 'utf-8');
    return $decoded;
}

/**
 * Convert ascii and special characters to html equivalent
 * @access public
 * @param string $string String to be cleaned
 * @return string returns Html encoded string
 */
function clean_text($string)
{
    $ci = &get_instance();
    $ci->load->helper('string');
    
    $clean = htmlentities( ascii_to_entities($string), ENT_QUOTES, 'utf-8', FALSE);
    return $clean;
}


//function changeCase($str, $case = 'readable')
//{
//    switch($case)
//    {
//        case 'human' :
//            $str_space      = preg_replace('/(\w+)([A-Z])/U', '\\1 \\2', $str);
//            $str_dash       = str_replace('-', ' ', $str_space);
//            $str_readable   = str_replace('_', ' ', $str_dash);
//            return $str_readable;
//            break;
//        case 'snake' :
//            $str_space      = preg_replace('/(\w+)([A-Z])/U', '\\1_\\2', $str);
//            $snake_dash      = str_replace('-', '_', $str_space);
//            $string_lower   = strtolower($snake_dash);
//            $str_snake      = str_replace(' ', '_', $string_lower);
//            return $str_snake;
//            break;
//        case 'dash' :
//            $str_space      = preg_replace('/(\w+)([A-Z])/U', '\\1_\\2', $str);
//            $dash_dash      = str_replace('_', '-', $str_space);
//            $string_lower   = strtolower($dash_dash);
//            $str_dash       = str_replace(' ', '-', $string_lower);
//            return $str_dash;
//            break;
//        case 'camel' :
//            $str_dash       = str_replace('-', ' ', $str);
//            $str_space      = str_replace('_', ' ', $str_dash);
//            $str_upper      = ucwords($str_space);
//            $str_no_space   = str_replace(' ', '', $str_upper);
//            $str_camel      = lcfirst($str_no_space);
//            return $str_camel;
//            break;
//        case 'pascal' :
//            $str_dash       = str_replace('-', ' ', $str);
//            $str_space      = str_replace('_', ' ', $str_dash);
//            $str_upper      = ucwords($str_space);
//            $str_pascal     = str_replace(' ', '', $str_upper);
//            return $str_pascal;
//            break;
//        default :
//            $str_space      = preg_replace('/(\w+)([A-Z])/U', '\\1_\\2', $str);
//            $snake_dash      = str_replace('-', '_', $str_space);
//            $string_lower   = strtolower($snake_dash);
//            $str_snake      = str_replace(' ', '_', $string_lower);
//            return $str_snake;
//            break;
//    }
//}

/* End of file api_helper.php */
/* Location: ./application/helpers/api_helper.php */